package cn.cs.service.impl;

import cn.cs.client.*;
import cn.cs.common.*;
import cn.cs.pojo.AgentShop;
import cn.cs.service.AgentManageService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AgentManageServiceImpl implements AgentManageService{
    @Resource
    private AgentUserClient agentUserClient;
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private AgentManageClient agentManageClient;
    @Resource
    private AgentUserForUserDB agentUserForUserDB;
    @Resource
    private AgentUserForShopDB agentUserForShopDB;
    @Resource
    private SysDtAreaClient sysDtAreaClient;
    @Resource
    private  AgentUserForOrderDB agentUserForOrderDB;
    @Override
    public Dto getAgentLevelB(HttpServletRequest request) throws Exception{
        String token = request.getHeader("token");
        Map<String,Object> agentUser =  JSON.parseObject(redisUtils.getString(token), Map.class);
        Map<String,Object> user = agentUserClient.getAgentUserByPhone(agentUser.get("phone").toString());
        String area = request.getParameter("area");
        Map<String,Object> param = new HashMap<String,Object>();
        if(EmptyUtils.isNotEmpty(area)){
            param.put("area",area);
        }
        param.put("code",user.get("invitation_code").toString());
        List<Map<String,Object>> list = agentManageClient.getAgentLevelBs(param);
        for(Map<String,Object> agent :list){
            Map<String,Object> shop = agentUserForShopDB.getAgentShopByAgentId(agent.get("id").toString());
            shop.put("is_power",agent.get("is_power"));
            shop.put("belong_area",getPCareaContent(agent.get("agent_area").toString()));
            shop.put("person",agent.get("person"));
            shop.put("level",agent.get("type_id"));
//            shop.put("belong_area",getPCareaContent(shop.get("shop_area").toString()));
        }
        Map<String,Object> retMap = new HashMap<String, Object>();
        if(EmptyUtils.isNotEmpty(list)){
            retMap.put("list",list);
            retMap.put("count",list.size());
            return DtoUtil.returnDataSuccess(retMap);
        }else{
            return DtoUtil.returnFail("没有找到市县级经理","002");
        }
    }
    public String getPCareaContent(String areaId) throws Exception{
        Map<String,Object> areaf = sysDtAreaClient.getSysDtAreaById(areaId);
        Map<String,Object> areas = sysDtAreaClient.getSysDtAreaById(areaf.get("area_parent_id").toString());
        Map<String,Object> areat = sysDtAreaClient.getSysDtAreaById(areas.get("area_parent_id").toString());
        return  areat.get("area_name")+" "+areas.get("area_name")+" "+areaf.get("area_name");
    }

    @Override
    public Dto getAgentShopInfo(HttpServletRequest request) throws Exception{
        String token = request.getHeader("token");
        Map<String,Object> agentUser =  JSON.parseObject(redisUtils.getString(token), Map.class);
        Map<String,Object> user = agentUserClient.getAgentUserByPhone(agentUser.get("phone").toString());
        Map<String,Object> shop = agentUserForShopDB.getAgentShopByAgentId(user.get("id").toString());
       if(EmptyUtils.isNotEmpty(shop)){
           shop.put("person",user.get("person"));
           shop.put("level",user.get("type_id"));
           shop.put("name",user.get("name"));
           shop.put("belong_area",getPCareaContent(user.get("agent_area").toString()));
           shop.put("agent_area",user.get("agent_area"));
           return DtoUtil.returnDataSuccess(shop);
       }else{
           return DtoUtil.returnFail("没有找到相关商铺信息","002");
       }
    }

    @Override
    public Dto setPower(HttpServletRequest request) {
        return null;
    }

    @Override
    public Dto getAgentLevelBCount(HttpServletRequest request) {
        String token = request.getHeader("token");
        Map<String,Object> agentUser =  JSON.parseObject(redisUtils.getString(token), Map.class);
        Map<String,Object> user = agentUserClient.getAgentUserByPhone(agentUser.get("phone").toString());
        Map<String,Object> param = new HashMap<String, Object>();
        param.put("code",user.get("invitation_code").toString());
        List<Map<String,Object>> list = agentManageClient.getAgentLevelBs(param);
        Map<String,Object> retMap = new HashMap<String, Object>();
        retMap.put("code",user.get("invitation_code").toString());
        retMap.put("count",list.size());
        return DtoUtil.returnDataSuccess(retMap);
    }

    @Override
    public Dto invitationAgentLevelB(HttpServletRequest request) throws Exception{
        String token = request.getHeader("token");
        Map<String,Object> agentUser =  JSON.parseObject(redisUtils.getString(token), Map.class);
        Map<String,Object> user = agentUserClient.getAgentUserByPhone(agentUser.get("phone").toString());
        String phone = request.getParameter("phone");
        Map<String,Object> agentLeveB =agentUserClient.getAgentUserByPhone(phone);
        if(EmptyUtils.isNotEmpty(agentLeveB)){
            return DtoUtil.returnFail("此手机号已注册，请换一个手机号","002");
        }
        String area = request.getParameter("area");
        int mu = 0;
        String id = IdWorker.getId();
        String level = "2";
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("invitation_code",user.get("invitation_code").toString());
        map.put("area",area);
        Map<String,Object> co = agentUserClient.getLevelBCount(map);
        if(EmptyUtils.isEmpty(co)){
            Map<String,Object> param = new HashMap<String, Object>();
            param.put("createDate",new Date());
            param.put("id", id);
            param.put("plan_id","");
            param.put("phone",phone);
            param.put("is_power","0");
            param.put("parent_invitation_code",user.get("invitation_code").toString());
            int n = agentUserForUserDB.getseqOfCity();
            param.put("invitation_code",user.get("invitation_code").toString()+String.format("%04d", n));
            param.put("type_id","2");
            mu =  agentManageClient.insertLevelB(param);
            if(mu>0){
                Map<String,Object> areaMap = new HashMap<String, Object>();
                areaMap.put("id",IdWorker.getId());
                areaMap.put("agent_area",area);
                areaMap.put("agent_id",id);
                areaMap.put("agent_level",level);
                areaMap.put("create_time",DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
                agentManageClient.insertAgentArea(areaMap);
                return DtoUtil.returnSuccess();
            }else{
                return DtoUtil.returnFail("添加失败","002");
            }
        }else {
            if ("1".equals(co.get("is_power"))) {
                return DtoUtil.returnFail("此区域已经邀请过管理员，不能重复邀请", "002");
            }
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("createDate", new Date());
            param.put("id", id);
            param.put("plan_id", "");
            param.put("phone", phone);
            param.put("is_power", "0");
            param.put("invitation_code", co.get("invitation_code").toString());
            param.put("parent_invitation_code", user.get("invitation_code").toString());
            param.put("type_id","2");
            mu = agentManageClient.insertLevelB(param);
            if (mu > 0) {
                Map<String, Object> areaMap = new HashMap<String, Object>();
                areaMap.put("agent_id", co.get("id").toString());
                areaMap.put("area", area);
                Map<String, Object> agentArea = agentManageClient.getAgentAreaByAgentId(areaMap);
                agentArea.put("agent_id", id);
                agentManageClient.updateAgentArea(agentArea);
                agentManageClient.deleteAgentUserById(co.get("id").toString());
                return DtoUtil.returnSuccess();
            } else {
                return DtoUtil.returnFail("添加失败", "002");
            }
        }
    }

    @Override
    public Dto invitationAgentLevelB2(HttpServletRequest request) {
        String token = request.getHeader("token");
        Map<String,Object> agentUser =  JSON.parseObject(redisUtils.getString(token), Map.class);
        Map<String,Object> user = agentUserClient.getAgentUserByPhone(agentUser.get("phone").toString());
        String phone = request.getParameter("phone");
        Map<String,Object> agentLeveC =agentUserClient.getAgentUserByPhone(phone);
        if(EmptyUtils.isNotEmpty(agentLeveC)){
            return DtoUtil.returnFail("此手机号已注册，请换一个手机号","002");
        }
        String id  = IdWorker.getId();
        Map<String,Object> param = new HashMap<String, Object>();
        param.put("createDate",new Date());
        param.put("id", id);
        param.put("plan_id","");
        param.put("phone",phone);
        param.put("is_power","0");
        param.put("parent_invitation_code",user.get("invitation_code").toString());
        param.put("invitation_code","");
        param.put("type_id","3");
        int mu =  agentManageClient.insertLevelB(param);
        if(mu>0){
            return DtoUtil.returnSuccess();
        }else{
            return DtoUtil.returnFail("添加失败","002");
        }
    }

    @Override
    public Dto dataAgentLeveB(HttpServletRequest request) {
        return null;
    }

    @Override
    public Dto devRepAndShop(HttpServletRequest request) {
        String token = request.getHeader("token");
        Map<String,Object> agentUser =  JSON.parseObject(redisUtils.getString(token), Map.class);
        Map<String,Object> user = agentUserClient.getAgentUserByPhone(agentUser.get("phone").toString());
        String code = user.get("invitation_code").toString();
        Map<String,Object> param = new HashMap<String, Object>();
        param.put("code",code);
      List<Map<String,Object>> areaList=  agentUserClient.getAgentAreasByAgentUserId(user.get("id").toString());
      String areas = "";
      for(Map<String,Object> m:areaList){
          areas = areas+ m.get("agent_area") +",";
      }
      if(EmptyUtils.isNotEmpty(areas)){
          areas = areas.substring(0,areas.length()-1);
      }
        param.put("areas",areas.split(","));
        List<Map<String,Object>> repList = agentUserForUserDB.getDevRepUsers(param);
        for(Map<String,Object> rep :repList){
            if(EmptyUtils.isNotEmpty(rep.get("personName"))){
                String personName =   rep.get("personName").toString();
                if(personName.length() == 3 || personName.length() ==2){
                    personName = personName.substring(0,1)+"师傅";
                }
                if(personName.length() == 4){
                    personName = personName.substring(0,2)+"师傅";
                }
                rep.put("personName",personName);
            }else{
                rep.put("personName","无师傅");
            }
        }
        List<Map<String,Object>> shopList = agentUserForUserDB.getDevShops(code);
        List<Map<String,Object>> agentList = agentUserClient.getAgentUsersByParentInviCode(code);
        Map<String,Object> retMap = new HashMap<String, Object>();
        retMap.put("repList",repList);
        retMap.put("shopList",shopList);
        retMap.put("agentList",agentList);
        return DtoUtil.returnDataSuccess(retMap);
    }

    @Override
    public Dto getNearShopInfo(HttpServletRequest request) throws Exception{
        String token = request.getHeader("token");
        Map<String,Object> agentUser =  JSON.parseObject(redisUtils.getString(token), Map.class);
        String id = request.getParameter("id");
        Map<String,Object> shop = agentUserForShopDB.getNearShopById(id);
        if(EmptyUtils.isNotEmpty(shop)){
            shop.put("address",getPCareaContent(shop.get("area").toString())+shop.get("address").toString());
            String[] pros = shop.get("product").toString().split(",");
            Map<String,Object> para = new HashMap<String, Object>();
            para.put("ids",pros);
            List<String> list = agentUserForOrderDB.getProsByShopId(para);
            shop.put("pros",list);
            return  DtoUtil.returnDataSuccess(shop);
        }else{
            return  DtoUtil.returnFail("没有找到此商铺","002");
        }
    }

    @Override
    public Dto addNearShop(HttpServletRequest request) throws Exception{
        String token = request.getHeader("token");
        Map<String,Object> agentUser =  JSON.parseObject(redisUtils.getString(token), Map.class);
        Map<String,Object> user = agentUserClient.getAgentUserByPhone(agentUser.get("phone").toString());
        String data = request.getParameter("data");
        Map<String,Object> shop =  JSONObject.parseObject(data);
        Map<String,Object> nearShop = agentUserForUserDB.getNearShopByMap(shop);
        if(EmptyUtils.isNotEmpty(nearShop)){
            return DtoUtil.returnSuccess();
        }
        String id  = IdWorker.getId();
        UploadInfo info= UploadUtil.fileUpload(request,"user/nearShopLogo/"+id);
        Map<String,Object> area = sysDtAreaClient.getSysDtAreaById(shop.get("area").toString());
        Map<String,Object> city = sysDtAreaClient.getSysDtAreaById(area.get("area_parent_id").toString());
        Map<String,Object> pri = sysDtAreaClient.getSysDtAreaById(city.get("area_parent_id").toString());
        String cityName = city.get("area_name").toString();
        String priName = pri.get("area_name").toString();
        shop.put("city",cityName);
        shop.put("province",priName);
        shop.put("id",id);
        shop.put("createDate",DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
        shop.put("code",user.get("invitation_code").toString());
        if(EmptyUtils.isNotEmpty(info)){
            shop.put("img","https://www.zzzsyh.com/image/user/nearShopLogo/"+id+"/"+info.getOldName());
        }
        int n = agentUserForUserDB.addNearShop(shop);
        if(n>0){
            String[] pros = shop.get("product").toString().split(",");
            Map<String,Object> typeMap =new HashMap<String, Object>();
            typeMap.put("shopId",id);
            for(String proId :pros){
                typeMap.put("typeId",proId);
                agentUserForUserDB.insertShopType(typeMap);
            }
            return DtoUtil.returnSuccess();
        }else{
            return DtoUtil.returnFail("添加失败","002");
        }
    }

    @Override
    public Dto setDefaultTX(HttpServletRequest request) {
        String token = request.getHeader("token");
        Map<String,Object> agentUser =  JSON.parseObject(redisUtils.getString(token), Map.class);
        Map<String,Object> user = agentUserClient.getAgentUserByPhone(agentUser.get("phone").toString());
        String type= request.getParameter("type");
        user.put("type",type);
        int n =agentUserClient.updateAgent(user);
        if(n>0){
            return DtoUtil.returnSuccess();
        }else{
            return DtoUtil.returnFail("更新失败","001");
        }
    }

    @Override
    public Dto getMainPros(HttpServletRequest request) {
        List<Map<String,Object>> list = agentUserForOrderDB.getMainPros();
        if(EmptyUtils.isNotEmpty(list)){
            return DtoUtil.returnDataSuccess(list);
        }else{
            return DtoUtil.returnFail("没有数据","002");
        }
    }
}
